package com.club.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangfc
 * @date 2022/12/13 9:16
 */
public class RequestHelper {

    final private static ThreadLocal<Map<String, Object>> THREAD_LOCAL = new ThreadLocal<>();

    private static void init() {
        //remove
        THREAD_LOCAL.remove();
        THREAD_LOCAL.set(new HashMap<>());
    }

    /**
     * 设置用户信息等
     *
     * @param uid      登陆人id
     * @param userName 登录人姓名
     */
    public static void setUserInfo(String uid, String userName) {
        //初始化ThreadLocal
        init();
        //
        final Map<String, Object> userMap = THREAD_LOCAL.get();
        userMap.put("id", uid);
        userMap.put("name", userName);
    }


    /**
     * 获取当前登陆人的用户名
     *
     * @return 用户名
     */
    public static String getUserName() {
        //本地测试的用户
        if (ObjectUtil.isEmpty(THREAD_LOCAL.get())) {
            return null;
        } else {
            return Convert.toStr(THREAD_LOCAL.get().get("name"));
        }
    }

    /**
     * 获取当前登陆人的id
     *
     * @return 用户id
     */
    public static String getId() {
        if (ObjectUtil.isEmpty(THREAD_LOCAL.get())) {
            return null;
        } else {
            return Convert.toStr(THREAD_LOCAL.get().get("id"));
        }
    }
}
